//
//  myCloudPageController.m
//  iOS_NongLian
//
//  Created by n369 on 16/3/3.
//  Copyright © 2016年 NongLian. All rights reserved.
//

#import "myCloudPageController.h"

@interface myCloudPageController () <UITableViewDataSource, UITableViewDelegate> {
    UITableView * _tableView;
    BOOL _open;
    NSInteger _lastOpen;
    NSMutableArray * _baseData;
    NSMutableArray * _dataSource;
    UISegmentedControl * _seg;
    //右边选项
    UIView * _view;
    BOOL _rightButtonOpen;
    //多选删除
    NSMutableArray * _deleteArray;
    UIView * _deleteView;
    UILabel * _choose;
}

@end

@implementation myCloudPageController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createNavigationBar:9];
    self.back.text = @"我的收藏";
    
    [self initData];
    [self createViews];
    [self createTableView];
//    self.navigationController.automaticallyAdjustsScrollViewInsets = NO;
    
}

- (void)initData {
    _open = 0;
    _lastOpen = -1;
    _rightButtonOpen = 0;
    _baseData = [[NSMutableArray alloc] initWithArray:@[@[@"种子种苗", @"露娜森",@"露娜森"],
                                                        @[@"农药", @"Row1_Subrow1", @"Row1_Subrow2", @"Row1_Subrow3", @"Row1_Subrow4", @"Row1_Subrow5", @"Row1_Subrow6", @"Row1_Subrow7"],
                                                        @[@"肥料", @"露娜森",@"露娜森"],
                                                        @[@"农机具", @"露娜森"],
                                                        @[@"其他", @"露娜森"]]];
    _dataSource = [[NSMutableArray alloc] init];
    for (NSArray * arr in _baseData) {
        if (arr.count > 1) {
            NSMutableArray * mutableArr = [[NSMutableArray alloc] initWithArray:arr];
            [mutableArr removeObjectAtIndex:0];
            [_dataSource addObjectsFromArray:mutableArr];
        }
    }
}

- (void)createTableView {
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 118, ScreenWidth, ScreenHeight - 118) style:UITableViewStyleGrouped];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.rowHeight = 100;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    [self.view addSubview:_tableView];
    [self.view addSubview:[Factory createViewWithBackgroundColor:RGB(216, 216, 216) frame:CGRectMake(0, 118, ScreenWidth, 0.5)]];
}


- (void)createViews {
    _seg = [[UISegmentedControl alloc] initWithItems:@[@"攻略", @"口袋书", @"发现"]];
    _seg.frame = CGRectMake(50, 75, ScreenWidth - 100, 30);
    _seg.selectedSegmentIndex = 0;
    _seg.tintColor = ColorNavigation;
    [_seg addTarget:self action:@selector(segAction:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:_seg];
}

- (void)segAction:(UISegmentedControl *)seg {
    [_tableView reloadData];
}

#pragma mark tableViewDatasource&Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (_seg.selectedSegmentIndex == 1 || _seg.selectedSegmentIndex == 2) {
        return _baseData.count;
    }
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_seg.selectedSegmentIndex == 1 || _seg.selectedSegmentIndex == 2) {
        if (_open == 0) {
            return 1;
        }
        if (_lastOpen == section) {
            NSArray * arr = _baseData[section];
            return arr.count;
        }
        return 1;
    }
    return _dataSource.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_seg.selectedSegmentIndex == 1 || _seg.selectedSegmentIndex == 2) {
        if (indexPath.row == 0) {
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
            cell.backgroundColor = [UIColor colorWithRed:237/255.0 green:237/255.0 blue:237/255.0 alpha:1];
            NSString * str = _baseData[indexPath.section][indexPath.row];
            UILabel * lable =[Factory createLabelWithTitle:str frame:CGRectMake(10, 10, 15 * str.length , 20) textColor:RGBA(1, 1, 1, .6) fontSize:14.f];
            [cell.contentView addSubview:lable];
            [cell.contentView addSubview:[Factory createLabelWithTitle:[NSString stringWithFormat:@"(%d)", 100] frame:CGRectMake(lable.right + 5, lable.top, 100, 20) textColor:RGBA(0, 0, 0, .4) fontSize:12.f]];
            [cell.contentView addSubview:[Factory createViewWithBackgroundColor:RGB(216, 216, 216) frame:CGRectMake(0, 0, ScreenWidth, .25)]];
            [cell.contentView addSubview:[Factory createViewWithBackgroundColor:RGB(216, 216, 216) frame:CGRectMake(0, 43.70, ScreenWidth, .25)]];
        }
            
            return cell;
        } else {
        }
    }
    UITableViewCell * goodCell = [tableView dequeueReusableCellWithIdentifier:@"goodCell"];
    if (!goodCell) {
        goodCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"goodCell"];
    }
    return goodCell;
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_tableView.editing) {
        NSArray *selectedRows = [_tableView indexPathsForSelectedRows];
        if (selectedRows.count == 0) {
            _choose.text = @"一个也没有选择";
        } else {
            _choose.text = [NSString stringWithFormat:@"已经选择了%ld个云单页", selectedRows.count];
        }
        
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_tableView.editing) {
        NSArray *selectedRows = [_tableView indexPathsForSelectedRows];
        if (selectedRows.count == 0) {
            _choose.text = @"一个也没有选择";
        } else {
            _choose.text = [NSString stringWithFormat:@"已经选择了%ld个云单页", selectedRows.count];
        }
        
    }
    if (_seg.selectedSegmentIndex == 1 || _seg.selectedSegmentIndex == 2) {
        if (indexPath.row == 0 && [_baseData[indexPath.section] count] == 1) {
            NSLog(@"sadf");
            return;
        }
        if (_open == 0) {
            if (indexPath.row == 0) {
                _open = 1;
                _lastOpen = indexPath.section;
            }
        } else {
            if (indexPath.row == 0) {
                if (_lastOpen == indexPath.section) {
                    _open = 0;
                    _lastOpen = -1;
                }
                _lastOpen = indexPath.section;
            }
        }
        [_tableView reloadData];
//        [_tableView reloadSections:[NSIndexSet indexSetWithIndex:_lastOpen] withRowAnimation:UITableViewRowAnimationAutomatic];
        if (indexPath.row != 0) {
            NSLog(@"sadf");
        }

    }
    NSLog(@"%ld", indexPath.row);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return .1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return .1;
    }
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_seg.selectedSegmentIndex == 1 || _seg.selectedSegmentIndex == 2) {
        if (indexPath.row == 0) {
            return 44;
        };
    }
    return 100;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 5)];
    view.backgroundColor = [UIColor whiteColor];
    return view;
}

- (void)backTitleAction {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)rightButtonAction {
    if (!_view) {
        _view = [[UIView alloc] initWithFrame:CGRectMake(ScreenWidth - 100, 63, 101, 0)];
        _view.backgroundColor = RGBA(255, 255, 255, .9);
//        _view.layer.shadowRadius = 1.f;
//        _view.layer.shadowColor = [UIColor blackColor].CGColor;
//        _view.layer.shadowOffset = CGSizeMake(-1, 1);
//        _view.layer.shadowOpacity = 0.5;
        _view.layer.borderWidth = 1.f;
        _view.layer.borderColor = RGB(216, 216, 216).CGColor;
        _view.clipsToBounds = YES;
        NSArray * arr = @[@"搜索", @"扫一扫", @"编辑"];
        for (int i = 0; i < 3; i++) {
            UIImageView * image = [[UIImageView alloc] initWithFrame:CGRectMake(10, i * 44 + 15, 14, 14)];
            image.image = [UIImage imageNamed:@"QRCodeIcon"];
            [_view addSubview:image];
            UILabel * lable = [Factory createLabelWithTitle:arr[i] frame:CGRectMake(image.right + 10, image.top, 40, 14) textColor:ColorNavigation fontSize:12];
            [_view addSubview:lable];
            UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(0, i * 44, 100, 44)];
            button.tag = 12 + i;
            [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
            [_view addSubview:button];
        }
        [self.view addSubview:_view];
    }
    if (!_rightButtonOpen) {
        [UIView animateWithDuration:.2 animations:^{
            _view.frame = CGRectMake(ScreenWidth - 100, 63, 101, 132);
        }];
        _rightButtonOpen = 1;
    } else {
        [UIView animateWithDuration:.2 animations:^{
            _view.frame = CGRectMake(ScreenWidth - 100, 63, 101, 0);
        }];
        _rightButtonOpen = 0;   
    }
}

- (void)buttonAction:(UIButton *)button {
    if (button.tag == 12) {
//        [self presentViewController:[NLianSearchViewController new] animated:YES completion:nil];
    }
    if (button.tag == 13) {
//        [self.tabBarController setSelectedIndex:2];
//        [self presentViewController:[NLianScanViewController new] animated:YES completion:nil];
    }
    if (button.tag == 14) {
        [self editAction];
    }
    [self rightButtonAction];
}

- (void)editAction {
    _tableView.editing = _tableView.editing ? NO :YES;
    _seg.selectedSegmentIndex = 0;
    [_tableView reloadData];
    [_seg setEnabled:_tableView.editing?NO:YES];
    if (!_deleteView) {
        _deleteView = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenHeight - 44, ScreenWidth, 44)];
        _deleteView.backgroundColor = [UIColor whiteColor];
        _deleteView.clipsToBounds = YES;
        _deleteView.alpha = 0;
        [_deleteView addSubview:HLine(0, 0, ScreenWidth)];
        [self.view addSubview:_deleteView];
        _choose = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 150, 20)];
        _choose.text = @"一个也没有选择";
        _choose.font = [UIFont systemFontOfSize:14];
        _choose.textColor = RGBA(1, 1, 1, .8);
        [_deleteView addSubview:_choose];
        UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(ScreenWidth * .6, 5, ScreenWidth * .4 - 10, 35)];
        button.backgroundColor = RGB(255, 51, 0);
        button.layer.cornerRadius = 3.f;
        [button setTitle:@"取消收藏" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:16];
        [button addTarget:self action:@selector(deleteButtonAction) forControlEvents:UIControlEventTouchUpInside];
        [_deleteView addSubview:button];
    }
    [UIView animateWithDuration:.2 animations:^{
        _deleteView.alpha = _tableView.editing?1:0;
        _tableView.frame = CGRectMake(0, 118, ScreenWidth, !_tableView.editing?(ScreenHeight - 118):(ScreenHeight - 118 - 45));
    }];
}

- (void)deleteButtonAction {
    // 选中的行
    NSArray *selectedRows = [_tableView indexPathsForSelectedRows];
    
    // 是否删除特定的行
    BOOL deleteSpecificRows = selectedRows.count > 0;
    // 删除特定的行
    if (deleteSpecificRows)
    {
        // 将所选的行的索引值放在一个集合中进行批量删除
        NSMutableIndexSet *indicesOfItemsToDelete = [NSMutableIndexSet new];
        
        for (NSIndexPath *selectionIndex in selectedRows)
        {
            [indicesOfItemsToDelete addIndex:selectionIndex.row];
        }
        // 从数据源中删除所选行对应的值
        [_dataSource removeObjectsAtIndexes:indicesOfItemsToDelete];
        
        //删除所选的行
        [_tableView deleteRowsAtIndexPaths:selectedRows withRowAnimation:UITableViewRowAnimationAutomatic];
    }

}

#pragma amrk -- tableView Del
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == (UITableViewCellEditingStyleDelete|UITableViewCellEditingStyleInsert)) {
        
//        [tableView deleteRowsAtIndexPaths:deleteArray withRowAnimation:UITableViewRowAnimationNone];
    }
}

// 是否可编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
// 编辑模式
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete|UITableViewCellEditingStyleInsert;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
